import { defineStore } from 'pinia'
import { ref } from 'vue'

export interface FormData {
  // 基本信息
  name: string
  gender: string
  age: number | null
  weight: number | null
  sampleNumber: string
  contactPhone: string
  sampleDate: string
  
  // 饮食习惯
  dietaryHabits: string[]
  
  // 其他信息
  remarks?: string
}

export const useFormStore = defineStore('form', () => {
  const formData = ref<FormData>({
    name: '',
    gender: '',
    age: null,
    weight: null,
    sampleNumber: '',
    contactPhone: '',
    sampleDate: '',
    dietaryHabits: [],
    remarks: ''
  })

  const isSubmitting = ref(false)
  const submitSuccess = ref(false)

  // 重置表单数据
  const resetForm = () => {
    formData.value = {
      name: '',
      gender: '',
      age: null,
      weight: null,
      sampleNumber: '',
      contactPhone: '',
      sampleDate: '',
      dietaryHabits: [],
      remarks: ''
    }
    submitSuccess.value = false
  }

  // 更新表单数据
  const updateFormData = (data: Partial<FormData>) => {
    formData.value = { ...formData.value, ...data }
  }

  // 验证表单数据
  const validateForm = (): { valid: boolean; errors: string[] } => {
    const errors: string[] = []

    if (!formData.value.name.trim()) {
      errors.push('请输入姓名')
    }

    if (!formData.value.gender) {
      errors.push('请选择性别')
    }

    if (!formData.value.age || formData.value.age <= 0) {
      errors.push('请输入有效年龄')
    }

    if (!formData.value.weight || formData.value.weight <= 0) {
      errors.push('请输入有效体重')
    }

    if (!formData.value.sampleNumber.trim()) {
      errors.push('请输入样本编号')
    }

    if (!formData.value.contactPhone.trim()) {
      errors.push('请输入联系方式')
    } else if (!/^1[3-9]\d{9}$/.test(formData.value.contactPhone)) {
      errors.push('请输入有效的手机号码')
    }

    if (!formData.value.sampleDate) {
      errors.push('请选择样本采集日期')
    }

    return {
      valid: errors.length === 0,
      errors
    }
  }

  // 设置提交状态
  const setSubmitting = (status: boolean) => {
    isSubmitting.value = status
  }

  // 设置提交成功状态
  const setSubmitSuccess = (status: boolean) => {
    submitSuccess.value = status
  }

  return {
    formData,
    isSubmitting,
    submitSuccess,
    resetForm,
    updateFormData,
    validateForm,
    setSubmitting,
    setSubmitSuccess
  }
}, {
  persist: {
    key: 'form-store',
    storage: localStorage,
    paths: ['formData']
  }
})